from PyQt5.QtCore import QThread, pyqtSignal
import os

class AudioSplitterThread(QThread):
    progress_updated = pyqtSignal(str, int, int, str)  # filename, current, total, temp_dir
    status_updated = pyqtSignal(str)  # status message
    finished = pyqtSignal(str)  # temp_dir
    error_occurred = pyqtSignal(str)  # error message

    def __init__(self, audio_path, output_dir, split_type="srt", subtitle_path=None, 
                 group_size=1, threshold=-30, output_format="wav"):
        super().__init__()
        self.audio_path = os.path.normpath(audio_path).replace('\\', '/')
        self.output_dir = os.path.normpath(output_dir).replace('\\', '/')
        self.split_type = split_type
        self.subtitle_path = os.path.normpath(subtitle_path).replace('\\', '/') if subtitle_path else None
        self.group_size = group_size
        self.threshold = threshold
        self.output_format = output_format

    def run(self):
        try:
            self.status_updated.emit("Initializing...")
            if self.split_type == "srt":
                if not self.subtitle_path:
                    raise ValueError("Subtitle path is required for SRT mode")
                temp_dir = split_audio_by_srt(
                    self.audio_path, 
                    self.subtitle_path, 
                    self.output_dir,
                    self.group_size,
                    self.progress_callback,
                    self.output_format
                )
            else:  # volume mode
                temp_dir = split_audio_by_volume(
                    self.audio_path,
                    self.output_dir,
                    1000,  # default time threshold
                    self.threshold,
                    self.progress_callback,
                    self.output_format
                )

            if temp_dir:
                self.status_updated.emit("Splitting completed!")
                self.finished.emit(temp_dir)
            else:
                self.error_occurred.emit("Error during splitting process")

        except Exception as e:
            self.error_occurred.emit(str(e))

    def progress_callback(self, filename, current, total, temp_dir=None):
        if isinstance(filename, str):
            if filename.startswith("Processing"):
                self.status_updated.emit(filename)
            else:
                self.status_updated.emit(f"Processing: {filename} ({current}/{total})")
                self.progress_updated.emit(filename, current, total, temp_dir or "") 